<template>
  <d2-container>
    <template slot="header">
      <el-form :gutter="24" ref="main-form" :model="mainQuery" label-position="left" :inline="true">
        <el-row>
          <el-form-item label="补单状态">
            <el-select v-model="mainQuery.handleStatus" clearable @change="fetchMainData">
              <el-option v-for="(item,index) in handleStatusList" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <div v-show="false">
        <el-upload class="upload-demo" accept=".xls , .xlsx" ref="upload" id="upload" :limit="1" :multiple="false" :file-list="fileList" action="#" :before-upload="BeforeUpload" :on-change="handleFileChange" :http-request="handleFileUpload" :on-success="handleFileUploadsucceed
                  ">
          <el-button size="small" type="primary" id="uploadBtn" ref="uploadBtn">上传补单号</el-button>
        </el-upload>
      </div>
      <div class="search-btn-box">

        <div class="left">
          <el-button-group style="display:flex">
            <el-button size="small" type="primary" @click="addFile">上传补单号</el-button>
            <el-button class="filter-item" icon="" :type="canCheck() ? 'success' : 'info'" @click="handleAction('check')" :disabled="!canCheck()" size="mini" v-if="
                $options.filters['checkButtonAccess'](
                  'tradeOrderForceSuccess-handleBatchReviewFirst'
                )
              ">初 审</el-button>
            <el-button class="filter-item" icon="" :type="canRecheck() ? 'success' : 'info'" @click="handleAction('recheck')" :disabled="!canRecheck()" size="mini" v-if="
                $options.filters['checkButtonAccess'](
                  'tradeOrderForceSuccess-handleBatchReviewSecond'
                )
              ">复 审</el-button>
            <el-button class="filter-item" style="margin-left:40px;" icon="el-icon-download" type="plain" @click="handleDownloadTemplate" size="mini">下载模板</el-button>

          </el-button-group>
        </div>
        <div class="right">
          <el-button class="filter-item" icon="el-icon-refresh" type="default" @click="resetMainData" :loading="mainTable.loading" size="mini">重置</el-button>
          <el-button class="filter-item" icon="el-icon-search" type="primary" @click="resetMainData" :loading="mainTable.loading" size="mini">查询</el-button>
        </div>
      </div>

    </template>
    <!--主列表数据-->
    <d2-crud ref="d2Crud" :options="mainTable.options" @custom-emit-handle-channel-down="downFile" :rowHandle="mainTable.rowHandle" :index-row="mainTable.indexRow" :columns="mainTable.columns" :data="mainTable.list" :selection-row="mainTable.allowSelect" :loading="mainTable.loading" @current-change="onMainCurrentChange" @row-dblclick="onMainDoubleClick"></d2-crud>
    <template slot="footer">
      <el-pagination @size-change="handleMainSizeChange" @current-change="handleMainPageChange" :current-page="mainTable.pagination.currentPage" :page-sizes="mainTable.pagination.pageSizes" :page-size="mainTable.pagination.pageSize" :page-count="mainTable.pagination.pageCount" :total="mainTable.pagination.total" layout="total, sizes, prev, pager, next, jumper" :background="true">
      </el-pagination>
    </template>
    <dialog-action ref="dialog-action" @dialog-close="fetchMainData"></dialog-action>
  </d2-container>
</template>

<script>
import ApiMain from '@/api/trans.checked';
import DialogAction from './dialog-action';
import util from '@/libs/util.js';
import { updataFileOss } from '@/api/tools.js'

export default {
  mixins: [
  ],
  props: [
  ],
  components: {
    DialogAction
  },
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      loading: false,
      handleStatusList: [
        { value: 0, label: '初审待审' },
        { value: 1, label: '初审通过' },
        { value: 2, label: '初审驳回' },
        { value: 3, label: '复审通过' },
        { value: 4, label: '复审驳回' }],
      mainQuery: {},
      file: [],
      mainTable: {
        loading: false,
        options: {
          border: true,
          stripe: true,
          highlightCurrentRow: true,
          emptyText: "暂无数据",
          size: "mini",
        },
        // indexRow: {
        //   title:'序号',
        //   width: "80",
        //   align:'center'
        // },
        indexRow: null,
        allowSelect: false,
        columns: [
          // 终端号
          { title: '批次号', key: 'batch', align: 'center', showOverflowTooltip: true },
          { title: '文件名', key: 'uploadFile', align: 'center', showOverflowTooltip: true },
          { title: '补单状态', key: 'strHandleStatus', align: 'center', showOverflowTooltip: true },
          { title: '创建时间', key: 'createTime', align: 'center', showOverflowTooltip: true },
          { title: '上传人', key: 'createBy', align: 'center', showOverflowTooltip: true },
        ],
        rowHandle: {
          width: '160',
          align: 'center',
          fixed: 'right',
          custom: [
            {
              text: '下载文件',
              type: 'primary',
              size: 'mini',
              emit: 'custom-emit-handle-channel-down'
            },

          ]
        },
        list: [{}, {}, {}],
        pagination: {
          currentPage: 1,
          pageSize: 50,
          total: 0,
          pageSizes: [50, 100, 200],
        },
        current: null,
      },
    }
  },

  created() {
    this.fetchMainData()
  },
  mounted() {
  },

  methods: {
    addFile() {
      document.getElementById("uploadBtn").click();
    },
    downFile(item) {
      var a = document.createElement("a");
      var event = new MouseEvent("click");
      a.download = item.row.uploadFile;
      a.href = item.row.uploadFile;
      a.dispatchEvent(event);
    },
    canCheck() {
      if (this.mainTable.loading) return false;
      if (!this.mainTable.current) return false;
      return this.mainTable.current.handleStatus == 0
    },

    canRecheck() {
      if (this.mainTable.loading) return false;
      if (!this.mainTable.current) return false;
      return this.mainTable.current.handleStatus == 1
    },

    renderMainData(re) {
      console.log('数据', re)
      this.mainTable.list = re.list;
      this.mainTable.pagination.total = re.total;

      console.log(this.mainTable.list)


    },

    handleMainSizeChange(val) {
      this.mainTable.pagination.pageSize = val;
      this.mainTable.pagination.currentPage = 1;
      this.fetchMainData();
    },
    handleMainPageChange(val) {
      this.mainTable.pagination.currentPage = val;
      this.fetchMainData();
    },

    buildMainQuery() {
      var query = {
        page: this.mainTable.pagination.currentPage,
        limit: this.mainTable.pagination.pageSize,
        search: this.mainQuery,
      };

      return query;
    },

    resetMainData() {
      this.fetchMainData();
    },

    onMainSelectionChange(now, old) {
      this.mainTable.selectionRow = now
    },


    handleSet() {

    },
    async fetchOptions() { },

    async fetchMainData() {
      this.mainTable.loading = true;
      try {
        var re = await ApiMain.list(this.buildMainQuery());
        this.renderMainData(re);
      } catch (err) { }

      this.mainTable.loading = false;
    },

    onMainCurrentChange(now, old) {
      console.log(now, '点击')
      this.mainTable.current = now;
    },

    onMainDoubleClick(now) {
      this.mainTable.current = now;
    },

    handleAction(action) {
      if (!!this.mainTable.current) {
        this.$refs['dialog-action'].show(Object.copy(this.mainTable.current), action);
      }
    },
    async handleFileUpload(params, type) {


      let data = await updataFileOss(params, type)

      return data.res
    },
    BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 10;
      if (!isRightSize) {
        this.$message.error("文件大小超过 10MB");
      }
      return isRightSize;
    },

    async handleFileUploadsucceed(file, fileList) {
      console.log('上传', file)
      console.log(this.$refs.upload)
      let data = await ApiMain.add({
        uploadFile: file.requestUrls[0]
      })
      this.fetchMainData()
      try {
        this.fileList = []
      } catch (error) {

        console.log(error)

      }
    },

    submit() {
      console.log(this.file)
      if (this.file.length == 0) {
        this.$message({ message: '请选择文件', type: 'error' });
        return
      }
      this.loading = true;
      this.$refs.upload.submit();
    },

    handleDownloadTemplate() {
      console.log( process.env.VUE_APP_TEMPLAT)
      var a = document.createElement("a");
      var event = new MouseEvent("click");
      a.download = '模板';
      a.href = process.env.VUE_APP_TEMPLATE;
      a.dispatchEvent(event);

    },

    handleFileChange(file, fileList) {
      this.file = fileList
    },

  }
}
</script>